﻿using System;
using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.Linq;
using System.Text;

using System.Data.Entity;
using INSTA.StockApplication.DAL;

namespace INSTA.StockApplication.BLL
{
    public static class User
    {

        public const int ADMINISTRATOR = 1;
        public const int EMPLOYEE = 2;
        public const int CUSTOMER = 3;
        
        public static bool AddUser(string nom, string prenom, string mail , string adresse , string cp
            , string ville , string pays , string telephone,int type)
        {
            var u = new UTILISATEUR();
            u.ADRESSE = adresse;
            u.CP = cp;
            u.MAIL = mail;
            u.NOM = nom;
            u.PAYS = pays;
            u.PRENOM = prenom;
            u.TELEPHONE = telephone;
            u.VILLE = ville;

            if(type == CUSTOMER)
            {
                //CLIENT
                var client = new Customer();
                return client.AddUser(u, type);

            }
            else
            {
                //EMPLOYEE
                var employee = new Employee();
                return employee.AddUser(u,type);
            }
        }
        
        public static bool UpdateUser(int id,string nom, string prenom, string mail , string adresse , string cp
            , string ville , string pays , string telephone)
        {
            var context = new ApplicationStockEntities();
            UTILISATEUR u = context.UTILISATEURs.First(i => i.ID == id);
            u.ADRESSE = adresse;
            u.CP = cp;
            u.MAIL = mail;
            u.NOM = nom;
            u.PAYS = pays;
            u.PRENOM = prenom;
            u.TELEPHONE = telephone;
            u.VILLE = ville;
            return save(context);
        }

        private static bool save(ApplicationStockEntities context)
        {
            try
            {
                context.SaveChanges();
            }
            catch (DbEntityValidationException e)
            {
                foreach (var s in e.EntityValidationErrors)
                {
                    Console.WriteLine("Entite : {0} etat {1} : ", s.Entry.Entity.GetType().Name, s.Entry.State);
                    foreach (var v in s.ValidationErrors)
                    {
                        Console.WriteLine("Propriete {0}, erreur {1} : ", v.PropertyName, v.ErrorMessage);
                    }
                }
                return false;
            }
            return true;
        }

        public static UTILISATEUR GetUsersInformations(int id)
        {
            ApplicationStockEntities context = new ApplicationStockEntities();
            return context.UTILISATEURs.First(i => i.ID == id);
        }

    }
}
